import math
import util

def pearson(data):
    correl = []
    for state, results in data.iteritems():
        nodes = results.keys()
        mfis = results.values()
        stdev = [math.sqrt(util.var(res)) for res in mfis]
        matrix = []
        for sx, x in zip(stdev, mfis):
            row = []
            for sy, y in zip(stdev, mfis):
                if sx == 0 or sy == 0:
                    row.append(0)
                else:
                    row.append(util.cov(x, y) / (sx * sy))
            matrix.append(row)
        correl.append({'state': state, 'nodes': results.keys(),
                       'matrix': matrix})
    return correl

def spearman(data):
    correl = []
    for state, results in data.iteritems():
        nodes = results.keys()
        mfis = map(util.ranks, results.values())
        stdev = [math.sqrt(util.var(res)) for res in mfis]
        matrix = []
        for sx, x in zip(stdev, mfis):
            row = []
            for sy, y in zip(stdev, mfis):
                if sx == 0 or sy == 0:
                    row.append(0)
                else:
                    row.append(util.cov(x, y) / (sx * sy))
            matrix.append(row)
        correl.append({'state': state, 'nodes': results.keys(),
                       'matrix': matrix})
    return correl
